/*
 * 
 */
package es.drOsu.game;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;

import com.google.ads.AdRequest;
import com.google.ads.AdView;
import com.openfeint.api.OpenFeint;
import com.openfeint.api.OpenFeintDelegate;
import com.openfeint.api.OpenFeintSettings;
import com.openfeint.api.resource.CurrentUser;
import com.openfeint.api.resource.User;

import es.drOsu.common.Constants;
import es.drOsu.common.SongsSQLiteHelper;
import es.drOsu.common.Tools;

// TODO: Auto-generated Javadoc
/**
 * The Class DrosuMain clase pincipal del juego con todas las opciones iniciales del mismo.
 */
public class DrosuMain extends Activity implements OnClickListener{

	/** The Constant TAG para el debug en el LogCat. */
    private static final String TAG = "drOsuMain";
    
    /** The fail loggin cuenta del número de intentos de conexión a Open Feint. */
    private int failLoggin=0;
    
    /** The flag Open Feint es para que no se cierre cuando este en Open Feint o en el About. */
    private boolean flagOpenFeintorAbout = false;
    
    /** The users. */
    private String [] users=null;
    
    /** The game mode. */
    private int gameMode = -1;
    
    /** The game difficulty. */
    private int gameDifficulty = -1;
    
    /** The m context contexto de la actividad. */
    Context mContext;
	/** Called when the activity is first created. */
	Typeface face =null;
    
	/** The handler. */
	private final MyHandler handler = new MyHandler();
	    
    /** The progress dialog. */
    private ProgressDialog progressDialog;
    
    
    /**
	 * The Class MyHandler.
	 */
    private class MyHandler extends Handler {
        
        /* (non-Javadoc)
         * @see android.os.Handler#handleMessage(android.os.Message)
         */
        @Override
        public void handleMessage(Message msg) {
           Log.d(TAG, "msg: "+msg.what);
        		
        		failLoggin++;
        		if(msg.what==1 && failLoggin<=5){
        			if(OpenFeint.isUserLoggedIn())
        	        	handler.sendEmptyMessage(0);
        	        else{
        	        	new Thread() {
                            @Override
        					public void run() {
                                 //Enviamos un mensaje al handler para que la Activity continue creandose.
                            	try {
        							sleep(10000);
        						} catch (InterruptedException e) {
        							// TODO Auto-generated catch block
        							e.printStackTrace();
        						}
        						OpenFeintSettings settings = new OpenFeintSettings(Constants.gameName, Constants.gameKey, Constants.gameSecret, Constants.gameID);	        
        				        OpenFeint.initialize(mContext, settings, new OpenFeintDelegate() {
        							@Override
        							public void userLoggedIn(CurrentUser user) {
        								// TODO Auto-generated method stub
        								super.userLoggedIn(user);					
        				                new Thread() {
        				                    @Override
        									public void run() {
        				                         //Enviamos un mensaje al handler para que la Activity continue creandose.
        				                         handler.sendEmptyMessage(0);
        				                    }
        				               }.start();
        							}
        				        });
                                 handler.sendEmptyMessage(1);
                            }
                       }.start();
        	        }
        		}else
        			progressDialog.dismiss();
        }
    }
    
    
    /* (non-Javadoc)
     * @see android.app.Activity#onCreate(android.os.Bundle)
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);       
        face=Typeface.createFromAsset(getAssets(), "fonts/BILLD.TTF");
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.main);
        mContext = this; 
       
        progressDialog = new ProgressDialog(this);
        progressDialog.setTitle(mContext.getResources().getString(R.string.please_wait));
        progressDialog.setMessage(mContext.getResources().getString(R.string.open_feint_loading));
        progressDialog.setCancelable(false);
        progressDialog.show();
        //if(Tools.checkConnectivity(mContext)){
	        OpenFeintSettings settings = new OpenFeintSettings(Constants.gameName, Constants.gameKey, Constants.gameSecret, Constants.gameID);	        
	        OpenFeint.initialize(mContext, settings, new OpenFeintDelegate() {
				@Override
				public void userLoggedIn(CurrentUser user) {
					// TODO Auto-generated method stub
					super.userLoggedIn(user);					
	                new Thread() {
	                    @Override
						public void run() {
	                         //Enviamos un mensaje al handler para que la Activity continue creandose.
	                         handler.sendEmptyMessage(0);
	                    }
	               }.start();
				}

	        	
	        });
	        if(OpenFeint.isUserLoggedIn())
	        	handler.sendEmptyMessage(0);
	        else{
	        	new Thread() {
                    @Override
					public void run() {
                         //Enviamos un mensaje al handler para que la Activity continue creandose.
                    	try {
							sleep(5000);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
                         handler.sendEmptyMessage(1);
                    }
               }.start();
	        }
        //}else{
        //	finish();
        //}        
        Button startButton = (Button) findViewById(R.id.start_button);
        startButton.setTypeface(face);
        startButton.setOnClickListener(this);
        Button scoreButton = (Button) findViewById(R.id.scores_button);
        scoreButton.setTypeface(face);
        scoreButton.setOnClickListener(this);
        Button settingsButton = (Button) findViewById(R.id.settings_button);
        settingsButton.setTypeface(face);
        settingsButton.setOnClickListener(this);
        Button barButton = (Button) findViewById(R.id.open_feint_button);
        barButton.setTypeface(face);
        barButton.setOnClickListener(this);
        Button exitButton = (Button) findViewById(R.id.exit_button);
        exitButton.setTypeface(face);
        exitButton.setOnClickListener(this);
        Button aboutButton = (Button) findViewById(R.id.about_button);
        aboutButton.setTypeface(face);
        aboutButton.setOnClickListener(this);
        
        AdView adView = (AdView)this.findViewById(R.id.AdMob);
        AdRequest request = new AdRequest();
        //request.addTestDevice(AdRequest.TEST_EMULATOR);
        //request.addTestDevice("527E3725F773AF4EB8D7BE441914A139");
        request.setTesting(true);
       
        adView.loadAd(request);
    }
    
    /* (non-Javadoc)
     * @see android.view.View.OnClickListener#onClick(android.view.View)
     */
    public void onClick(View v){
    	switch (v.getId()){
	    	case R.id.start_button:
	    		openNewGameDialog(mContext);
	    		break;
	    	case R.id.scores_button:
	    		Intent intentScoreBoard = new Intent(mContext, ScoreBoard.class);
				Bundle bundle = new Bundle();
				bundle.putString(Constants.keyUser, OpenFeint.getCurrentUser().userID());
				intentScoreBoard.putExtras(bundle);
				startActivity(intentScoreBoard);
	    		break;
	    	case R.id.settings_button:
	    		Intent intentSettings= new Intent(mContext,Settings.class);
	    		startActivity(intentSettings);
	    		//Intent intentOrientation = new Intent(mContext, Orientation.class);
	    		//startActivity(intentOrientation);
	    		break;
	    	case R.id.open_feint_button:
	    		flagOpenFeintorAbout=true;
	    		Intent intentOpenFeint = new Intent(this, com.openfeint.api.ui.Dashboard.class);
	    		startActivity(intentOpenFeint);
	    		//Intent intentBar = new Intent(mContext, ShakeBar.class);
	    		//startActivity(intentBar);
	    		break;
	    	case R.id.exit_button:
	    		finish();
	    		break;
	    	case R.id.about_button:
	    		flagOpenFeintorAbout=true;
	    		Intent intentAbout = new Intent(mContext,About.class);
	    		startActivity(intentAbout);
	    		break;
	    }
    	
    }
    
    /* (non-Javadoc)
     * @see android.app.Activity#onKeyDown(int, android.view.KeyEvent)
     */
    @Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
    	switch (keyCode) {
			case KeyEvent.KEYCODE_BACK:
				
				return false;
			default:
				return super.onKeyDown(keyCode, event);
    	}
    	
	}
    
    /**
     * Open new game dialog para que el jugador vaya eligiendo modo, dificultad y usuario.
     *
     * @param context the context contexto de la actividad
     */
    private void openNewGameDialog(final Context context) {
    	
    	new AlertDialog.Builder(context).setTitle(R.string.game_mode_title).
    		setItems(R.array.game_mode,new DialogInterface.OnClickListener() {
    			public void onClick(DialogInterface dialoginterface,int i) {
    				gameMode = i;
    				new AlertDialog.Builder(context).setTitle(R.string.game_difficulty_title).
    				setItems(R.array.game_difficulty,new DialogInterface.OnClickListener() {    					
						@Override
						public void onClick(DialogInterface dialoginterface, int j) {
							// TODO Auto-generated method stub
							gameDifficulty=j;
							String userID = OpenFeint.getCurrentUser().userID();
							SharedPreferences prefs = getSharedPreferences(userID,Context.MODE_PRIVATE);
							if(!prefs.contains(Constants.sharedPreferencesUsers)){						
								SharedPreferences.Editor editor = prefs.edit();
								editor.putString(Constants.sharedPreferencesUsers, Constants.sharedPreferencesUsersCheck);
								editor.commit();
							}
							if(!prefs.contains(Constants.sharedPreferencesSoundsEffects)){
								SharedPreferences.Editor editor = prefs.edit();
								editor.putString(Constants.sharedPreferencesSoundsEffects, Constants.sharedPreferencesSoundEffectsUncheck);
								editor.commit();
							}
							if(!prefs.contains(Constants.sharedPreferencesGraphicsEffects)){
								SharedPreferences.Editor editor = prefs.edit();
								editor.putString(Constants.sharedPreferencesGraphicsEffects, Constants.sharedPreferencesGraphicsEffectsCheck);
								editor.commit();
							}
							Bundle bundle = new Bundle();
							bundle.putString(Constants.keyUser, userID);
							bundle.putInt(Constants.keyGameMode, gameMode);
							bundle.putInt(Constants.keyGameDifficulty, gameDifficulty);
							if(prefs.contains(Constants.sharedPreferencesSongs)){
									Log.d(TAG, "si prefs");
									if(SongsSQLiteHelper.getPathSongs(mContext, userID)!=null){
										Log.d(TAG, "entra en game si prefs");
										Intent intentGame = new Intent(context,Game.class);
										intentGame.putExtras(bundle);
					    	    		startActivity(intentGame);
									}else{
										Log.d(TAG, "entra en songs si prefs");
										Intent intentSongs = new Intent(context,Songs.class);
										intentSongs.putExtras(bundle);
					    	    		startActivity(intentSongs);
									}
							}else{
								Log.d(TAG, "entra en songs no prefs");
								SharedPreferences.Editor editor = prefs.edit();
								editor.putString(Constants.sharedPreferencesSongs, Constants.sharedPreferencesSongsCheck);
								editor.commit();
								Intent intentSongs = new Intent(context,Songs.class);
								intentSongs.putExtras(bundle);
			    	    		startActivity(intentSongs);
							}
						}
					}).show();
				}
    		}).show();

    }
    
    /* (non-Javadoc)
     * @see android.app.Activity#onRestart()
     */
    @Override
    public void onRestart(){
    	super.onRestart();
    	finish();
    }
    /* (non-Javadoc)
     * @see android.app.Activity#onPause()
     */
    @Override
    protected void onPause(){
            super.onPause();
            Log.d(TAG, "onPause()");
            if(!flagOpenFeintorAbout)
        		finish();
        	else
        		flagOpenFeintorAbout=false;
    }
    
}